package com.zhiyou.user.service.impl;

import com.zhiyou.user.dao.UserDao;
import com.zhiyou.user.pojo.User;
import com.zhiyou.user.service.UserService;
import com.zhiyou.user.util.FtpUtil;
import com.zhiyou.user.util.IDUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.DateTime;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void update(User user) {
        userDao.updateByPrimaryKeySelective(user);
    }

    @Override
    public String updateImage(Integer id, MultipartFile uploadFile) {
        //1、给上传的图片生成新的文件名
        //1.1获取原始文件名
        String oldName = uploadFile.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀
        String newName = IDUtils.genImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        //1.3生成文件在服务器端存储的子目录
        String filePath = new DateTime().toString("/yyyyMMdd/");

        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //2.2调用FtpUtil工具类进行上传
        String userImage=FtpUtil.putImages(input, filePath, newName);
        User user = userDao.selectByPrimaryKey(id);
        String imgs = user.getImgs();
        user.setImgs(userImage);
        userDao.updateByPrimaryKey(user);
        String[] split = imgs.split("/");
        FtpUtil.delImages("/"+split[split.length-2]+"/"+split[split.length-1]);
        return userImage;
    }

    @Override
    public void sendSms(Integer id) {
        String checkcode = RandomStringUtils.randomNumeric(6);
        //向缓存中留一份
        redisTemplate.opsForValue().set("checkcode_"+id.toString(),checkcode,6, TimeUnit.HOURS);
        //给用户发一份
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile",userDao.selectByPrimaryKey(id).getMoble());
        map.put("checkcode",checkcode);
        rabbitTemplate.convertAndSend("sms",map);
    }
}
